import Axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
// const timeOut = 10000 // 24 hours
// function isTimeOut () {
//   const newTime = Date.now()
//   const setTime = (newTime - store.state.user.lowTime) / 1000 // s
//   return setTime > timeOut
// }
const request = Axios.create({
  baseURL: 'https://likede2-admin.itheima.net/likede/',
  timeout: 5000
})
request.interceptors.request.use(
  (config) => {
    // if (store.state.user.userList.token) {
    //   if (isTimeOut()) {
    //     Message.error('登录过期 请重新登录')
    //     // store.dispatch('user/getlogAction')
    //     // router.push('/login')
    //     return
    //   }
    // }
    // config.headers.Authorization = `Bearer ${store.getters.token}`
    store.state.user.token &&
      (config.headers.authorization = `${store.state.user.token}`)
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  (res) => {
    if (res.status === 200) {
      // Message.success(res.data.msg)
      return res.data
    } else {
      // Message.error(res.data.msg)
      return Promise.reject(new Error(res.data.msg))
    }
    // return res.data
  },
  (err) => {
    if (err.response.status === 401) {
      Message.error('登录过期 请重新登录')
      store.dispatch('user/tologinAction')
      router.push('/login')
    } else {
      Message.error(err.response.data.message && err.response.data.message || err.response.data)
    }
    return Promise.reject(err)
  }
)
export default request
